//
//  SRUserInfoEditViewController.m
//  StoryShow
//
//  Created by CyonLeuMBP on 2017/4/25.
//  Copyright © 2017年 qudiandu.cn. All rights reserved.
//

#import "SRUserInfoEditViewController.h"

#import "FZUserSettingModel.h"
#import "SRPersonalCenterConstant.h"
#import <SRUploadQiniuManager.h>
#import "SRPersonalServices.h"

#import "SRUserInfoTableViewCell.h"
#import "FZTextInputViewController.h"
#import "RSKImageCropViewController.h"
#import "SRValuePickerView.h"
#import <UIImage+Enhanced.h>
#import "SRClassConstants.h"


@interface SRUserInfoEditViewController ()<UITableViewDataSource, UITableViewDelegate,  UIAlertViewDelegate, RSKImageCropViewControllerDelegate, RSKImageCropViewControllerDataSource, UIImagePickerControllerDelegate,UINavigationControllerDelegate, UIActionSheetDelegate>

@property (strong, nonatomic) UITableView *tableView;
@property (strong, nonatomic) NSMutableArray *items;

@property (strong, nonatomic) UIImage *avatarImage;
@property (strong, nonatomic) NSString *qiniuImageName;
@property (strong, nonatomic) NSString *nickname;
@property (strong, nonatomic) NSString *schoolName;
@property (strong, nonatomic) NSString *grageString;
@property (strong, nonatomic) NSString *ageString;
@property (strong, nonatomic) NSString *sexString;
@property (strong, nonatomic) NSString *schoolTypeString;

@property (assign, nonatomic) NSInteger schoolType;

@property (assign, nonatomic) NSInteger gradeInt;
@property (assign, nonatomic) NSInteger age;
@property (assign, nonatomic) NSInteger sex;//1男，2女
@property (assign, nonatomic) BOOL isChangedUserInfo;
@property (assign, nonatomic) BOOL isChangedSchoolType;


@property (strong, nonatomic) RSKImageCropViewController *imageCropVC;
@property (strong, nonatomic) SRValuePickerView *valuePickerView;//
@property (strong, nonatomic) NSArray *pickItems;//
@property (strong, nonatomic) UIButton *saveButton;

@end

@implementation SRUserInfoEditViewController

- (void)viewDidLoad {
    [super viewDidLoad];
        // Do any additional setup after loading the view.
    
    self.title = @"我的信息";
    [self setupData];
    [self setupView];
    [self setupValuePickerView];
    
    [self getUserSettingConfig];
    
    self.isChangedUserInfo = NO;
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
        // Dispose of any resources that can be recreated.
}

#pragma mark - setup

- (void)doBack {
    if (self.isChangedUserInfo) {
            //提示保存
        WEAKSELF
        UIAlertView *alertView = [UIAlertView alertViewWithTitle:@"保存修改" message:@"您有未保存的修改，确定要退出吗？" cancelButtonTitle:@"退出" didDismissBlock:^(UIAlertView *alertView, NSInteger buttonIndex) {
            if (buttonIndex == 0) {
                    //保存
                [weakSelf uploadUserInfoToServer];
                
            } else {
                [weakSelf.navigationController popViewControllerAnimated:YES];
            }
        } otherButtonTitles:@"保存", nil];
        
        [alertView show];
    } else {
        [super doBack];
    }
}

- (void)setupData {
        //test data
    self.items = [@[] mutableCopy];

}

- (void)setupView {
    
        //    WEAKSELF
    
    FZStyleSheet *css = [FZStyleSheet currentStyleSheet];
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.rowHeight = 85;
    if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"9.0")) {
        self.tableView.cellLayoutMarginsFollowReadableWidth = NO;
    }
    [self.tableView registerNib:[UINib nibWithNibName:kSRUserInfoTableViewCell bundle:nil] forCellReuseIdentifier:kSRUserInfoTableViewCell];
    
    [self.view addSubview:self.tableView];
    
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.contentInset = UIEdgeInsetsMake(10, 0, 0, 0);
    self.tableView.tableFooterView = [[UIView alloc] init];
    
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.bottom.top.equalTo(self.view);
    }];
    self.view.backgroundColor = self.tableView.backgroundColor = css.color_2;
    
    [self setupNavigationItem];
}

- (void)setupNavigationItem {
    
    FZStyleSheet *css = [FZStyleSheet currentStyleSheet];
    UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
    rightButton.frame = CGRectMake(0, 0, 40, 40);
    [rightButton setTitle:@"保存" forState:UIControlStateNormal];
    rightButton.titleLabel.font = css.fontOfH4;
    
    self.saveButton = rightButton;
    [rightButton addTarget:self action:@selector(onSaveButton:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
    
    [self setRightBarButtonItem:rightItem];
}

- (void)setupValuePickerView {
    
    self.valuePickerView = [[SRValuePickerView alloc] init];
}

- (void)getUserSettingConfig {
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"UserInfoEditConfig" ofType:@"json"];
    NSData *data = [NSData dataWithContentsOfFile:filePath];
    NSDictionary *jsonDictionary = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
    NSArray *sectionJSONArray = jsonDictionary[@"config_data"];
    NSArray *modelArray = [MTLJSONAdapter modelsOfClass:[FZUserSettingModel class] fromJSONArray:sectionJSONArray error:nil];
    self.items = [modelArray mutableCopy];

    for (FZUserSettingModel *item in self.items) {
        if ([item.identifier isEqualToString:userinfo_avatar]) {
                //头像
            item.iconName = [SRLoginUser avatar];
            
            item.subtitle = nil;
        }
        else if ([item.identifier isEqualToString:userinfo_nickname]) {
                //昵称
            item.subtitle = [SRLoginUser nickname];
        }
        else if ([item.identifier isEqualToString:userinfo_school]) {
                //学校
//            item.subtitle = [SRLoginUser schoolName];
            NSString *school = [SRLoginUser schoolName];
            if (school) {
                self.schoolName = school;
                item.subtitle = school;
            } else {
                item.subtitle = @"还没设置学校";
            }
        }
        else if ([item.identifier isEqualToString:userinfo_grade]) {
                //年级
            NSString *gradeString = [SRLoginUser schoolGrade];
            if (gradeString) {
                self.gradeInt = [gradeString integerValue];
                if (self.gradeInt > 0) {
                    gradeString = [NSString stringWithFormat:@"%@年级", gradeString];
                    self.grageString = gradeString;
                }
                else {
                    gradeString = @"还没有设置年级";
                }
                
            } else {
                gradeString = @"还没有设置年级";
                self.gradeInt = 0;
            }
            
            item.subtitle = gradeString;
        }
        else if ([item.identifier isEqualToString:userinfo_age]) {
                //年龄
            NSInteger age = [SRLoginUser age];
            if (age > 0) {
                self.age = age;
                
                item.subtitle = [NSString stringWithFormat:@"%d岁", (int)age];
                self.ageString = item.subtitle;
                
            } else {
                item.subtitle = @"还没设置年龄";
                self.age = 0;
            }
        }
        else if ([item.identifier isEqualToString:userinfo_sex]) {
                //性别
                //年龄
            NSInteger sex = [SRLoginUser sex];
            if (sex > 0) {
                
                if (sex == 1) {
                    item.subtitle = [NSString stringWithFormat:@"男"];
                } else {
                    item.subtitle = [NSString stringWithFormat:@"女"];
                }
                self.sexString = item.subtitle;
                self.sex = sex;
            } else {
                self.sex = 0;
                item.subtitle = @"还没设置性别";
            }
        }
        else if ([item.identifier isEqualToString:userinfo_changeSchoolIdenty]) {
                //性别
            
            NSInteger userType = [SRLoginUser schoolIdentity];
            if (userType > 0) {
                
                if (userType == 1) {
                    item.subtitle = [NSString stringWithFormat:@"学生"];
                } else {
                    item.subtitle = [NSString stringWithFormat:@"老师"];
                }
                self.schoolTypeString = item.subtitle;
                self.schoolType = userType;
            } else {
                self.schoolType = 0;
                item.subtitle = @"还没设置身份";
            }
        }
    }
    
    [self.tableView reloadData];
}


#pragma mark - Event

- (void)toChangeAvatar {
    UIActionSheet *myActionSheet = [[UIActionSheet alloc]
                                    initWithTitle:nil
                                    delegate:self
                                    cancelButtonTitle:@"取消"
                                    destructiveButtonTitle:nil
                                    otherButtonTitles: @"从相册选择", @"拍照",nil];
//    myActionSheet.tintColor = [FZStyleSheet currentStyleSheet].color_1;
    
    [myActionSheet showInView:self.view];
}

- (void)toChangeNickname {
    WEAKSELF
    FZTextInputViewController *vc = [[FZTextInputViewController alloc] init];
    vc.maxInputTextCount = 16;
    vc.minInputTextCount = 2;
    vc.tipTitle = @"修改昵称";
    
    vc.didChangeInputTextBlock = ^(NSString *inputText) {
        weakSelf.nickname = inputText;
        [SRLoginUser setNickname:inputText];
        [weakSelf updateCellDataWithID:userinfo_nickname value:inputText];

    };
    
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)toChangeSchoolName {
    WEAKSELF
    FZTextInputViewController *vc = [[FZTextInputViewController alloc] init];
    vc.tipTitle = @"修改学校";
    vc.maxInputTextCount = 16;
    vc.minInputTextCount = 2;

    vc.didChangeInputTextBlock = ^(NSString *inputText) {
        weakSelf.schoolName = inputText;
        [SRLoginUser setSchoolName:inputText];

        [weakSelf updateCellDataWithID:userinfo_school value:inputText];
    };
    
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)toChangeGrade {
    
    NSMutableArray *dataArray = [@[] mutableCopy];
    for (int i = 1; i <= 12; ++ i) {
        NSString *gradeString = [NSString stringWithFormat:@"%d年级", i];
        [dataArray addObject:gradeString];
    }
    
//    self.pickItems = @[@"1年级", @"2年级", @"3年级", @"4年级", @"5年级", @"6年级", @"7年级", @"8年级", @"9年级", @"10年级", @"11年级", @"12年级"];
    
    self.valuePickerView.dataSource = dataArray;
    self.valuePickerView.pickerTitle = @"所在年级";
    WEAKSELF
    self.valuePickerView.valueDidSelectBlock = ^(NSString *value, NSInteger selectedRow){
        weakSelf.grageString = value;

        weakSelf.gradeInt = selectedRow + 1;
        [SRLoginUser setSchoolGrade:[@(weakSelf.gradeInt) stringValue]];

        [weakSelf updateCellDataWithID:userinfo_grade value:value];
    };
    
    [self.valuePickerView show];
}

- (void)toChangeAge {
    NSMutableArray *dataArray = [@[] mutableCopy];
    for (int i = 3; i <= 60; ++ i) {
        NSString *gradeString = [NSString stringWithFormat:@"%d岁", i];
        [dataArray addObject:gradeString];
    }
    
    self.valuePickerView.dataSource = dataArray;
    self.valuePickerView.pickerTitle = @"年龄";
    WEAKSELF
    self.valuePickerView.valueDidSelectBlock = ^(NSString *value, NSInteger selectedRow){
        weakSelf.ageString = value;
        weakSelf.age = selectedRow + 3;
        [SRLoginUser setAge:weakSelf.age];
        [weakSelf updateCellDataWithID:userinfo_age value:value];
    };
    
    [self.valuePickerView show];
}

- (void)toChangeSex {
    NSMutableArray *dataArray = [@[@"男", @"女" ] mutableCopy];
    
    self.valuePickerView.dataSource = dataArray;
    self.valuePickerView.pickerTitle = @"性别";
    WEAKSELF
    self.valuePickerView.valueDidSelectBlock = ^(NSString *value, NSInteger selectedRow){
        weakSelf.sexString = value;
        weakSelf.sex = selectedRow + 1;
        [SRLoginUser setSex:weakSelf.sex];
        
        [weakSelf updateCellDataWithID:userinfo_sex value:value];
    };
    
    [self.valuePickerView show];
}

- (void)toChangeSchoolIdenty {
    NSMutableArray *dataArray = [@[@"学生", @"老师" ] mutableCopy];
    
    self.valuePickerView.dataSource = dataArray;
    self.valuePickerView.pickerTitle = @"身份";
    WEAKSELF
    self.valuePickerView.valueDidSelectBlock = ^(NSString *value, NSInteger selectedRow){
        weakSelf.schoolTypeString = value;
        weakSelf.schoolType = selectedRow + 1;
        [SRLoginUser setSchoolIdentity:weakSelf.schoolType];
        
        [weakSelf uploadUserSchoolTypeToServer];
        
        [weakSelf updateCellDataWithID:userinfo_changeSchoolIdenty value:value];
    };
    
    [self.valuePickerView show];
}
- (void)updateCellDataWithID:(NSString *)identifier value:(NSString *)value {
    for (FZUserSettingModel *item in self.items) {
        if ([item.identifier isEqualToString:identifier]) {
            item.subtitle = value;
            
            if ([identifier isEqualToString:userinfo_changeSchoolIdenty]) {
                
            } else {
                self.isChangedUserInfo = YES;
            }
            break;
        }
    }
    
    [self.tableView reloadData];
}

- (void)setIsChangedUserInfo:(BOOL)isChangedUserInfo {
    _isChangedUserInfo = isChangedUserInfo;
    
    [self.saveButton setEnabled:isChangedUserInfo];
}

- (void)onSaveButton:(id)sender {
    if (self.isChangedUserInfo) {
        [self uploadUserInfoToServer];
    }
}
- (void)uploadUserSchoolTypeToServer {
    
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    [params setValue:@(self.schoolType) forKey:@"user_type"];
    
    WEAKSELF
    
    [SRPersonalServices editUserInfo:params successBlock:^(NSInteger statusCode, NSString *message, id responseDataObject) {
        [weakSelf stopProgressHUD];
        if (statusCode == kFZRequestStatusCodeSuccess) {
            [weakSelf showHUDHintWithText:@"修改身份成功"];
            weakSelf.isChangedUserInfo = NO;
            if (responseDataObject) {
                [[SRLoginManager sharedManager] updateUserInfo:responseDataObject];
            }
            
            [[NSNotificationCenter defaultCenter] postNotificationName:kSRSchoolUserTypeDidChangeNotification object:nil];
            
//            [weakSelf performSelector:@selector(doBack) withObject:nil afterDelay:1];
            
        } else {
            [weakSelf showHUDErrorMessage:message];
        }
    } failureBlock:^(id responseObject, NSError *error) {
        [weakSelf stopProgressHUD];
        [weakSelf showHUDErrorMessage:@"保存失败"];
    }];
}

- (void)uploadUserInfoToServer {
    
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    [params setValue:self.nickname forKey:@"nickname"];
    [params setValue:@(self.sex) forKey:@"sex"];
    [params setValue:self.schoolName forKey:@"school"];

    [params setValue:@(self.gradeInt) forKey:@"grade"];
    [params setValue:@(self.age) forKey:@"age"];
    [params setValue:self.qiniuImageName forKey:@"avatar"];
    [params setValue:@(self.schoolType) forKey:@"user_type"];
    
    WEAKSELF
    
    [SRPersonalServices editUserInfo:params successBlock:^(NSInteger statusCode, NSString *message, id responseDataObject) {
        [weakSelf stopProgressHUD];
        if (statusCode == kFZRequestStatusCodeSuccess) {
            [weakSelf showHUDHintWithText:@"保存成功"];
            weakSelf.isChangedUserInfo = NO;
            if (responseDataObject) {
                [[SRLoginManager sharedManager] updateUserInfo:responseDataObject];
            }
            
            [weakSelf performSelector:@selector(doBack) withObject:nil afterDelay:1];
            
        } else {
            [weakSelf showHUDErrorMessage:message];
        }
    } failureBlock:^(id responseObject, NSError *error) {
        [weakSelf stopProgressHUD];
        [weakSelf showHUDErrorMessage:@"保存失败"];
    }];
}

#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [self.items count];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    SRUserInfoTableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:kSRUserInfoTableViewCell forIndexPath:indexPath];
    FZUserSettingModel *item = self.items[indexPath.row];
    [cell updateCellInfo:item];
    
    if ([item.identifier isEqualToString:userinfo_avatar]) {
        if (self.avatarImage) {
            [cell setIconImage:self.avatarImage];
        }
    }
    
    return cell;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    FZUserSettingModel *item = self.items[indexPath.row];
    if ([item.identifier isEqualToString:userinfo_avatar]) {
        return 85;
    } else {
        return 60;
    }
}

#pragma mark - UITableViewDelegate


//-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
//    return 0.01;
//}
//-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
//    return 10;
//}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    FZUserSettingModel *item = self.items[indexPath.row];
    if ([item.identifier isEqualToString:userinfo_avatar]) {
            //头像
        [self toChangeAvatar];
    }
    else if ([item.identifier isEqualToString:userinfo_nickname]) {
            //昵称
        [self toChangeNickname];
    }
    else if ([item.identifier isEqualToString:userinfo_school]) {
            //学校
        [self toChangeSchoolName];
    }
    else if ([item.identifier isEqualToString:userinfo_grade]) {
            //年级
        [self toChangeGrade];
    }
    else if ([item.identifier isEqualToString:userinfo_age]) {
            //年龄
        [self toChangeAge];
    }
    else if ([item.identifier isEqualToString:userinfo_sex]) {
            //性别
        [self toChangeSex];
    }
    else if ([item.identifier isEqualToString:userinfo_changeSchoolIdenty]) {
            //身份
        [self toChangeSchoolIdenty];
    }
}

#pragma mark - UIAcitonSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex
{
    switch (buttonIndex) {
        case 0:
                //从相册选择
            [self LocalPhoto];
            break;
        case 1:
                //拍照
            [self takePhoto];
            break;
        default:
            break;
    }

}

#pragma mark - Take photo image

    //从相册选择
-(void)LocalPhoto{
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        //资源类型为图片库
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    picker.delegate = self;
        //设置选择后的图片可被编辑
    picker.allowsEditing = NO;
    [self  presentViewController:picker animated:YES completion:nil];
}

    //拍照
-(void)takePhoto{
        //资源类型为照相机
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
        //判断是否有相机
    if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]){
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
            //设置拍照后的图片可被编辑
        picker.allowsEditing = NO;
            //资源类型为照相机
        picker.sourceType = sourceType;
        [self  presentViewController:picker animated:YES completion:nil];
    }else {
        NSLog(@"该设备无摄像头");
    }
}


#pragma Delegate method UIImagePickerControllerDelegate
    //图像选取器的委托方法，选完图片后回调该方法

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    UIImage *image = info[UIImagePickerControllerOriginalImage];
    [picker dismissViewControllerAnimated:YES completion:nil];
    
    RSKImageCropViewController *imageCropVC = [[RSKImageCropViewController alloc] initWithImage:image cropMode:RSKImageCropModeCircle];
    imageCropVC.delegate = self;
//    imageCropVC.dataSource = self;
    self.imageCropVC = imageCropVC;
    
    [self.navigationController pushViewController:imageCropVC animated:YES];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker;
{
    [picker dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - RSKImageCropViewControllerDelegate

- (void)imageCropViewControllerDidCancelCrop:(RSKImageCropViewController *)controller
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)imageCropViewController:(RSKImageCropViewController *)controller didCropImage:(UIImage *)croppedImage usingCropRect:(CGRect)cropRect
{
        //当图片不为空时显示图片并保存图片
    if (croppedImage != nil) {
        self.avatarImage = croppedImage;
        if (self.didChangeAvatarImageBlock) {
            self.didChangeAvatarImageBlock(self.avatarImage);
        }
        
        self.isChangedUserInfo = YES;
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
        SRUserInfoTableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
        if (cell) {
            [cell setIconImage:croppedImage];
        }
        
        [self uploadImageToServerWithImage:croppedImage];
    }
    
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - RSKImageCropViewControllerDataSource

- (BOOL)isPortraitInterfaceOrientation {
    return YES;
}

- (CGRect)imageCropViewControllerCustomMaskRect:(RSKImageCropViewController *)controller {
    CGFloat height = MAX(200, SCREEN_WIDTH * 200.0 / 375.0);
    CGSize maskSize = CGSizeMake(SCREEN_WIDTH, height);
    
    CGFloat viewWidth = CGRectGetWidth(controller.view.frame);
    CGFloat viewHeight = CGRectGetHeight(controller.view.frame);
    
    CGRect maskRect = CGRectMake((viewWidth - maskSize.width) * 0.5f,
                                 (viewHeight - maskSize.height) * 0.5f,
                                 maskSize.width,
                                 maskSize.height);
    
    return maskRect;
}
    // Returns a custom path for the mask.
- (UIBezierPath *)imageCropViewControllerCustomMaskPath:(RSKImageCropViewController *)controller
{
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRect:controller.maskRect];
    return maskPath;
}

- (UIImage *)scaleToSize:(UIImage *)img size:(CGSize)size
{
        // 创建一个bitmap的context
        // 并把它设置成为当前正在使用的context
    UIGraphicsBeginImageContext(size);
        // 绘制改变大小的图片
    [img drawInRect:CGRectMake(0, 0, size.width, size.height)];
        // 从当前context中创建一个改变大小后的图片
    UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
        // 使当前的context出堆栈
    UIGraphicsEndImageContext();
        // 返回新的改变大小后的图片
    return scaledImage;
}

- (NSString *)typeForImageData:(NSData *)data {
    
    
    uint8_t c;
    
    [data getBytes:&c length:1];
    
    
    
    switch (c) {
            
        case 0xFF:
            
            return @"jpeg";
            
        case 0x89:
            
            return @"png";
            
        case 0x47:
            
            return @"gif";
            
        case 0x49:
            
        case 0x4D:
            
            return @"tiff";
            
    }
    
    return @"jpeg";
    
}

- (NSString *)dateString {
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.dateFormat = @"yyyy-MM-dd";
    NSString *dayString = [dateFormatter stringFromDate:[NSDate date]];
    NSString *timeInterval = [NSString stringWithFormat:@"%lld", (long long)[NSDate timeIntervalSince1970]];
    return [NSString stringWithFormat:@"uid%@_%@_%@", [SRLoginUser userID], dayString, timeInterval];
}

- (void)uploadImageToServerWithImage:(UIImage *)image {
    
    if (![SRLoginUser uploadPicToken]) {
        [self showHUDErrorMessage:@"图片上传失败picToken不存在"];
        return;
    }
    
    [self startProgressHUDWithText:@"正在上传..."];
    
    CGFloat maxImageWidth = 200;
    
    UIImage *uploadImage =  [image compressedImage:image maxWidth:maxImageWidth];
    
    NSData *compressImageData =  UIImageJPEGRepresentation(uploadImage, 0.4);
//    UIImage *compressImage = [UIImage imageWithData:compressImageData];
//    self.avatarImage = compressImage;
    
    NSString *imageExstion = [self typeForImageData:compressImageData];
    NSString *imageFileName = [NSString stringWithFormat:@"userAvatar_%@.%@",[self dateString], imageExstion];
    
        //指定新建文件夹路径
    NSString *imageDocPath = [CacheDirectory stringByAppendingPathComponent:@"ImageFile"];
        //创建ImageFile文件夹
    [[NSFileManager defaultManager] createDirectoryAtPath:imageDocPath withIntermediateDirectories:YES attributes:nil error:nil];
        //保存图片的路径
    NSString *imagePath  = [imageDocPath stringByAppendingPathComponent:imageFileName];
    [[NSFileManager defaultManager] createFileAtPath:imagePath contents:compressImageData attributes:nil];
    self.qiniuImageName = imageFileName;
    WEAKSELF
        //上传图片到七牛云端
    [[SRUploadQiniuManager sharedInstance] uploadFileToQiNiuForPath:imagePath key:imageFileName uploadToken:[SRLoginUser uploadPicToken] UploadPercent:^(NSString *key, float percent) {
        
    } responseBlock:^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
        if (info.isOK) {
                //上传成功
                //删除本地存储的图片文件
            NSLog(@"上传图片成功:%@", key);
            [weakSelf stopProgressHUD];
            [weakSelf showHUDErrorMessage:@"上传成功"];
            
            weakSelf.qiniuImageName = key;
        } else {
                //上传数据失败
            NSLog(@"上传图片失败：%@", resp);
            NSString *message = [NSString stringWithFormat:@"图片上传失败ErrorCode(%d):%@", info.statusCode, resp];
            [weakSelf showHUDErrorMessage:message];
        }
    }];

}



@end
